<template>
  <view class="content">
    <!-- 顶部菜单栏 -->
    <view class="banner">
      <view class="left-container">
        <img src="/static/images/logo.png" alt="" class="logo" />
        <text>JinPin</text>
      </view>
      <view class="menu-container" @click="toggleMenu">
        <img src="/static/images/menu.png" alt="" class="menu" />
      </view>
    </view>

    <!-- 下拉菜单 -->
    <view class="dropdown-menu" :class="{ show: showMenu }">
      <!-- 主菜单列表 -->
      <view class="menu-list main-list">
        <view class="menu-item" v-for="(item, index) in menuList" :key="index">
          <view class="menu-item-content">
            <img :src="item.icon" class="menu-icon" />
            <text>{{ item.name }}</text>
          </view>
          <view>></view>
        </view>
      </view>
    </view>

    <!-- 主内容区 -->
    <view class="main-content">
      <scroll-view class="scroll-container" scroll-x enable-flex>
        <view class="card" v-for="b in banners" :key="b.id" @click="goDetail(b.id)">
          <image :src="b.img" class="card-image" mode="aspectFill" />
          <view class="card-content">
            <view class="card_title">
              <text>{{ b.title }}</text>
              <img v-if="b.verified" src="/static/images/gou.png" class="gou" />
            </view>
            <text class="card-text">{{ b.description }}</text>
          </view>
        </view>
      </scroll-view>
    </view>

    <!-- 时下流行 -->
    <view style="margin-bottom: 20px">
      <view class="time-title" style="display: flex; margin-bottom: 20px; gap: 15rpx">
        <text style="font-weight: bolder; font-size: 20px">时下流行</text>
        <img src="/static/images/heart.png" style="width: 45rpx; height: 45rpx" />
      </view>
      <view class="time-content">
        <scroll-view scroll-x="true" class="scroll-view_H" enable-flex="true">
          <view class="time-card" v-for="w in hotList" :key="w.id" @click="goDetail(w.id)">
            <image :src="w.img" class="time-card-image" mode="aspectFill" />
            <view class="time-card-title">
              <view class="top-row">
                <view style="
                    display: flex;
                    gap: 10rpx;
                    display: flex;
                    align-items: center;
                  ">
                  <text class="author-name">{{ w.author }}</text>
                  <img src="/static/images/gou.png" alt="" style="width: 20px; height: 20px" />
                </view>
                <button class="like" :class="[{ active: w.liked }, { pulse: w.animating }]" @click.stop="likeWork(w)">
                  <img src="/static/images/hana1.png" style="width: 20rpx; height: 20rpx" />
                  <text>{{ w.likeCount }}</text>
                </button>
              </view>
              <text class="card-name">{{ w.name }}</text>
            </view>
          </view>
        </scroll-view>
      </view>
    </view>

    <!-- 最近卖出 -->
    <view>
      <view style="
          display: flex;
          align-items: center;
          margin-bottom: 20px;
          gap: 15rpx;
        ">
        <text style="font-size: 20px; font-weight: bolder">最近卖出</text>
        <img src="/static/images/earth.png" alt="" style="width: 20px; height: 20px" />
      </view>
      <view class="grid-container">
        <view class="grid-card" v-for="g in recentSold" :key="g.id" @click="goDetail(g.id)">
          <image :src="g.img" class="grid-image" mode="aspectFill" />
          <view class="grid-title">
            <text>{{ g.name }}</text>
            <image v-if="g.verified" src="/static/images/gou.png" class="verified-icon" />
          </view>
          <view class="grid-footer">
            <text class="price">￥{{ g.price }}</text>
            <view class="likes">
              <img src="/static/images/heart.png" class="heart-icon" />
              <text>{{ g.likeCount }}</text>
            </view>
          </view>
        </view>
      </view>
    </view>

    <view v-if="!hotList.length" class="skeleton-hot"></view>
  </view>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive } from "vue";
import { http } from "@/pages/utils/Http";
import type { HomeResponse } from "@/pages/utils/request";
import { onPullDownRefresh, onShow } from "@dcloudio/uni-app";

const showMenu = ref(false);

// 首页动态数据
const banners = ref<any[]>([]);
const categories = ref<any[]>([]);
const hotList = ref<any[]>([]);
const recentSold = ref<any[]>([]);

// 在声明 categories 等后添加
const menuList = categories;

// add likeLocks map
const likeLocks = reactive<Record<number, boolean>>({});

// 添加数据刷新控制
let lastRefreshTime = 0;
const REFRESH_INTERVAL = 1000; // 1秒内不重复刷新

// 抽离成独立函数，便于首次加载与下拉刷新共用
const fetchHomeData = async () => {
  try {
    const userId = uni.getStorageSync("userId") || 0;
    console.log("首页加载 - 从本地存储获取的 userId:", userId);

    const res = await http.get<HomeResponse>(`/api/home?userId=${userId}`);
    if (res.code === 200) {
      console.log("首页加载 - /api/home 返回数据 =", res.data);
      banners.value = res.data.banners;
      categories.value = res.data.categories;

      // 确保点赞状态正确初始化
      hotList.value = res.data.hotList.map((w: any) => {
        const work = {
          ...w,
          desc: w.description || w.desc, // 兼容后端返回的字段名
          liked: !!w.liked,
          likeCount: Number(w.likeCount ?? w.like_count ?? 0),
          animating: false,
        };
        console.log(`首页加载 - 作品 ${w.id} 点赞状态:`, {
          liked: work.liked,
          likeCount: work.likeCount,
          originalLiked: w.liked,
          originalLikeCount: w.likeCount ?? w.like_count
        });
        return work;
      });

      recentSold.value = res.data.recentSold;
      console.log("首页加载 - 热门列表处理完成，共", hotList.value.length, "个作品");
    }
  } catch (e) {
    console.error("首页加载 - 获取数据失败:", e);
  }
};

// 首次加载
onMounted(fetchHomeData);

// 页面显示时刷新数据（从详情页返回时）
onShow(() => {
  const now = Date.now();
  if (now - lastRefreshTime > REFRESH_INTERVAL) {
    console.log("首页页面显示，刷新数据...");
    fetchHomeData();
    lastRefreshTime = now;
  } else {
    console.log("首页页面显示，但距离上次刷新时间太短，跳过刷新");
  }
});

// 下拉刷新
onPullDownRefresh(async () => {
  await fetchHomeData();
  // 结束刷新动画
  uni.stopPullDownRefresh();
});

//控制菜单导航的显示与隐藏
const toggleMenu = () => {
  showMenu.value = !showMenu.value;
};

const goDetail = (id: number) => {
  uni.navigateTo({ url: `/pages/Detail/Detail?id=${id}` });
};

// 点赞 / 取消点赞
const likeWork = async (work: any) => {
  // 防止连续点击
  if (likeLocks[work.id]) return;
  likeLocks[work.id] = true;

  const userId = uni.getStorageSync("userId");
  console.log("首页点赞 - 从本地存储获取的 userId:", userId);
  console.log("首页点赞 - userId 类型:", typeof userId);

  if (!userId) {
    uni.showToast({ title: "请先登录", icon: "none" });
    likeLocks[work.id] = false;
    return;
  }

  // 保存请求前的状态，用于失败时回滚
  const prevLiked = work.liked;
  const prevLikeCount = work.likeCount;

  // 乐观更新：立即更新UI状态
  work.liked = !prevLiked;
  work.likeCount += work.liked ? 1 : -1;

  // 心跳动画
  work.animating = true;
  setTimeout(() => (work.animating = false), 300);

  try {
    const url = `/api/works/${work.id}/${prevLiked ? "unlike" : "like"}`;
    const requestData = { userId: Number(userId) };
    console.log("首页点赞 - 发送请求数据:", requestData);
    console.log("首页点赞 - 请求URL:", url);

    const res = await http.post<any>(url, requestData);

    if (res.code === 200) {
      // 使用后端返回的最新点赞数，确保数据一致性
      if (typeof res.likeCount !== "undefined") {
        work.likeCount = Number(res.likeCount);
      }
      console.log("首页点赞 - 操作成功，最新点赞数:", work.likeCount);
    } else {
      throw new Error(res.message || "操作失败");
    }
  } catch (e) {
    // 请求失败，回滚到之前的状态
    work.liked = prevLiked;
    work.likeCount = prevLikeCount;
    console.error("首页点赞 - 操作失败:", e);
    uni.showToast({ title: "操作失败", icon: "none" });
  } finally {
    // 延迟释放锁，防止快速连续点击
    setTimeout(() => {
      likeLocks[work.id] = false;
    }, 500);
  }
};
</script>

<style lang="scss" scoped>
.content {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  overflow-y: auto;
  box-sizing: border-box;
  padding: 20px;
  padding-top: 140rpx;
  /* 预留固定顶栏空间 */
  display: flex;
  flex-direction: column;
  margin: 0 auto;
}

.menu-item-content {
  display: flex;
  align-items: center;
  gap: 20rpx;
}

.menu-icon {
  width: 40rpx;
  /* 图标大小 */
  height: 40rpx;
}

.content {
  padding: 20px;
  padding-top: 140rpx;
  /* 预留固定顶栏空间 */
  display: flex;
  flex-direction: column;
  margin: 0 auto;
  position: relative;
}

.banner {
  box-sizing: border-box;
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  background: #fff;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx 10rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
  z-index: 9999;

  .left-container {
    display: flex;
    align-items: center;

    .logo {
      width: 80rpx;
      height: 80rpx;
      margin-right: 20rpx;
    }

    text {
      font-size: 40rpx;
      font-weight: bold;
      color: #000;
    }
  }

  .menu-container {
    .menu {
      width: 50rpx;
      height: 50rpx;
    }
  }
}

.dropdown-menu {
  position: fixed;
  top: 100rpx;
  left: 0;
  right: 0;
  background: #fff;
  max-height: 0;
  overflow: hidden;
  transition: max-height 0.5s cubic-bezier(0.36, 1, 0.36, 1);
  box-shadow: 0 10rpx 30rpx rgba(0, 0, 0, 0.1);
  z-index: 1000;

  &.show {
    max-height: 1500rpx;
  }

  .menu-list {
    padding: 20rpx 30rpx;

    &.main-list {
      display: flex;
      flex-direction: column;
      justify-content: space-between;
      align-items: center;
    }
  }

  .menu-item {
    padding: 25rpx;
    font-size: 32rpx;
    width: 100%;
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    align-items: center;
    position: relative;

    &::after {
      content: "";
      position: absolute;
      bottom: -20rpx;
      display: block;
      width: 100%;
      height: 1rpx;
      background: #eee;
      margin: 20rpx 0;
    }

    &:hover {
      background-color: #f5f5f5;
    }

    .highlight {
      font-weight: bold;
    }
  }
}

.main-content {
  width: 100%;
  margin-bottom: 20px;

  .scroll-container {
    width: 100%;
    white-space: nowrap;
    overflow-x: auto;
    display: flex;
    flex-wrap: nowrap;
    border-radius: 16px;

    /* 隐藏滚动条 */
    ::-webkit-scrollbar {
      display: none;
    }

    .card-image {
      height: 400rpx;
      width: 100%;
      object-fit: cover;
    }
  }
}

/* 顶部卡片容器 */
.scroll-container {
  width: 100%;
  white-space: nowrap;
  overflow-x: auto;
  display: flex;
  padding-bottom: 20rpx;
  border: radius 16px;

  .card {
    width: 600rpx;
    height: 540rpx;
    /* 图片 400 + 内容 140 */
    border: 1px solid #eee;
    border-radius: 16px;
    overflow: hidden;
    display: inline-flex;
    flex-direction: column;
    flex-shrink: 0;
    margin-right: 30rpx;
    background: #fff;
    box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.08);

    &:last-child {
      margin-right: 0;
    }

    .card-image {
      width: 100%;
      height: 400rpx;
      object-fit: cover;
    }

    .card-content {
      background: #fff;
      padding: 24rpx;
      display: flex;
      flex-direction: column;
      gap: 12rpx;
      height: 160rpx;
      /* 固定高度，可完整显示标题 + 两行简介 */
      overflow: hidden;
    }

    .card_title {
      width: 100%; // 确保标题占满宽度
      display: flex;
      justify-content: flex-start;
      align-items: center;
      gap: 20rpx;
      margin-bottom: 10rpx;
      /* 缩小间距 */

      text {
        font-size: 32rpx;
        font-weight: bold;
        text-align: left;
      }

      .gou {
        width: 35rpx;
        height: 35rpx;
      }
    }

    .card-text {
      width: 100%;
      font-size: 26rpx;
      color: #666;
      line-height: 1.4;
      text-align: left;
      display: -webkit-box;
      -webkit-line-clamp: 2;
      -webkit-box-orient: vertical;
      overflow: hidden;
    }
  }
}

.scroll-view_H {
  width: 100%;
  white-space: nowrap;
  overflow-x: auto;
  display: flex;
  flex-wrap: nowrap;
  border-radius: 16px;

  ::-webkit-scrollbar {
    display: none;
  }
}

.time-card {
  position: relative;
  width: 400rpx;
  border-radius: 16px;
  overflow: hidden;
  display: inline-flex;
  flex-direction: column;
  flex-shrink: 0;
  /* 防止卡片被压缩 */
  margin-right: 30rpx;
  /* 卡片间距 */
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
  border: 1px solid #eee;

  .time-card-image {
    width: 100%;
    height: 250rpx;
  }

  &:last-child {
    margin-right: 0;
  }
}

.like {
  width: 120rpx;
  height: 42rpx;
  border: none;
  border-radius: 30rpx;
  background-color: #f8f8f8;
  display: flex;
  justify-content: center;
  align-items: center;
  outline: none;
  gap: 5rpx;
  text-align: end;
  position: absolute;
  right: 20rpx;

  text {
    font-size: 12px;
  }

  transition: transform 0.2s ease;

  &.pulse {
    transform: scale(1.2);
  }

  &.active {
    background-color: #ffecec;
    color: #ff4d4f;
  }
}

button::after {
  border: none !important;
}

.time-card-title {
  display: flex;
  flex-direction: column;
  padding: 16rpx 20rpx 20rpx;

  .top-row {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 10rpx;
  }

  .author-name {
    font-size: 26rpx;
    font-weight: 500;
    color: #333;
  }

  .card-name {
    font-size: 28rpx;
    font-weight: 600;
    color: #000;
  }
}

.small-icon {
  border-radius: 10rpx;
  /* 根据需求调整 */
  box-shadow: 0 2rpx 5rpx rgba(0, 0, 0, 0.1);
  /* 可选阴影效果 */
  border: #fff 5px solid;
}

.recent-sold {
  margin-top: 40rpx;
  padding: 0 20rpx;
}

.section-header {
  display: flex;
  align-items: center;
  margin-bottom: 30rpx;
  gap: 15rpx;

  .section-title {
    font-size: 36rpx;
    font-weight: bold;
  }

  .section-icon {
    width: 40rpx;
    height: 40rpx;
  }
}

.grid-container {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
  gap: 20rpx;
}

.grid-card {
  width: calc(50% - 10rpx);
  /* 每行两个，考虑间隙 */
  border: 1px solid #eee;
  border-radius: 16rpx;
  padding: 20rpx;
  box-sizing: border-box;
  background: #fff;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);

  .grid-image {
    width: 100%;
    height: 200rpx;
    border-radius: 12rpx;
    object-fit: cover;
    margin-bottom: 20rpx;
  }

  .grid-title {
    display: flex;
    align-items: center;
    gap: 10rpx;
    margin-bottom: 10rpx;

    text {
      font-size: 28rpx;
      font-weight: bold;
    }

    .verified-icon {
      width: 30rpx;
      height: 30rpx;
    }
  }

  .grid-name {
    display: block;
    font-size: 26rpx;
    color: #666;
    margin-bottom: 20rpx;
  }

  .grid-footer {
    display: flex;
    justify-content: space-between;
    align-items: center;

    .price {
      font-size: 28rpx;
      font-weight: bold;
      color: #ff4d4f;
    }

    .likes {
      display: flex;
      align-items: center;
      gap: 5rpx;
      font-size: 24rpx;
      color: #999;

      .heart-icon {
        width: 25rpx;
        height: 25rpx;
      }
    }
  }
}

.skeleton-hot {
  height: 200px;
  background-color: #f0f0f0;
  border-radius: 10px;
  margin-top: 20px;
}
</style>
